# -*- coding:utf-8 -*-
"""
@Author : 审心
@Time : 2023/3/23 9:59
任务映射
"""
import time
import traceback

from autoTask.operaitonAid.taobao.get_store_info_module.get_store_info import StoreInfo
from autoTask.operaitonAid.utils.custom_errors import LoginError
from autoTask.taobao.sycm.gjc.competitorGoodKey import CompetitorGoodKey, CategorySearch
from autoTask.taobao.sycm.goods.findMarketRank import FindMarketRankV2, FindMarketRankToSystem
from autoTask.taobao.sycm.utils.close_Ad import tb_slider
from autoTask.taobao.taobao_login import Login
from autoTask.taobao.ztc.gjc import OptiBid
from common.utils import Base64Util, web_page_util, ExcelUtil, DateUtil
from common.logger.log import log_
from autoTask.pinduoduo.Login_v2 import PinDuoDuo as PinDuoDuo_Login
from autoTask.taobao.sycm.gjc.gjc_hyc_robot.gjc_hyc_main.gjc_hyc_main_run import run as gjc_hyc_run
from ScreenScribe.project_video_record import screen
from autoTask.operaitonAid.taobao.search_ranking_module.searchRank import SearchRank
from autoTask.operaitonAid.taobao.correlation_analysis_module.relatedAnalysis import RelatedAnalysis
from autoTask.operaitonAid.utils.request_data import requests_data
from autoTask.operaitonAid.taobao.task_run_module.task_run import product_single_task
import backoff


def test(snapshot, other):
    log_.info(f"任务执行完毕 : {snapshot, other} ")


def find_market_rank(snapshot, other):
    """
    获取市场排行商品
    :param other:
    :param snapshot:
    :return:
    """
    param = snapshot.get('param')
    page = web_page_util.create_page()
    try:
        Login(param.get("tbAccount"), param.get('tbPassword'), page).execute(
            url="https://sycm.taobao.com/portal/home.htm")
        tb_slider(page, timeout=10)
        path = FindMarketRankV2.builder_by_dict(page, param)()
        if path is None:
            return
        return {
            'task_file_base64': Base64Util.file_to_base64(path),
            'task_file_suffix': "zip"
        }
    finally:
        ExcelUtil.xw_close_all_excel()


def competitor_good_key(snapshot, other):
    """
    竞品词
    :param other:
    :param snapshot:
    :return:
    """
    param = snapshot.get('param')
    is_test_execute = snapshot.get("isTestExecute")
    # 解析参数
    category_search_list = param.get("categorySearchList") if param.get("categorySearchList") else []
    category_search_list = [CategorySearch.init_by_dict(category_search, "goodsFeatureList", "name") for category_search
                            in
                            category_search_list]
    page = web_page_util.create_page()
    try:
        Login(param.get("tbAccount"), param.get('tbPassword'), page).execute(
            url="https://sycm.taobao.com/portal/home.htm")
        tb_slider(page, timeout=10)
        result_path, file_suffix = CompetitorGoodKey(page=page,
                                                     category_search_list=category_search_list,
                                                     ignore_keys=param.get("ignoreKeys"),
                                                     competing_min_visits=param.get("competingMinVisits"),
                                                     competing_min_roi=param.get("competingMinRoi"),
                                                     is_test_execute=is_test_execute,
                                                     key_is_not_contain_letter=param.get("keyIsNotContainLetter")
                                                     if param.get("keyIsNotContainLetter") else False)()
        if result_path is None:
            return
        return {
            'task_file_base64': Base64Util.file_to_base64(result_path, is_test_execute),
            'task_file_suffix': file_suffix
        }
    finally:
        if not is_test_execute:
            # page.quit()
            ExcelUtil.xw_close_all_excel()


def ztc_gjc_opti_bid(snapshot, other):
    """
    直通车修改关键词出价
    :param other:
    :param snapshot:
    :return:
    """
    param = snapshot.get('param')
    is_test_execute = snapshot.get("isTestExecute")
    p = web_page_util.create_page()

    Login(param.get("bAccount"), param.get('bPassword'), p).execute(
        url="https://subway.simba.taobao.com/index.jsp")
    tb_slider(p, timeout=10)
    obj = OptiBid.Main.init_by_params(param)
    obj.is_test_execute = is_test_execute
    obj(p)


def task_gjc_hyc_run(snapshot, other):
    param = snapshot.get('param')
    param["isTestExecute"] = snapshot.get("isTestExecute")
    param["Screen"] = snapshot.get("Screen")
    log_.info(f"任务参数 : param {param}")
    if param["ScreenAction"]:
        # 如果开启录屏，就录屏
        screen.start_capture()
    page = web_page_util.create_page()
    try:
        Login(param.get("account"), param.get('password'), page).execute(
            url="https://sycm.taobao.com/portal/home.htm")
        tb_slider(page, timeout=10)

        competing_path, _ = CompetitorGoodKey(page=page,
                                              category_search_list=[
                                                  CategorySearch.init_by_dict(param, "targetProductMap",
                                                                              "searchContent")],
                                              ignore_keys=param.get("blockWords"),
                                              competing_min_visits=param.get("competingMinVisits"),
                                              competing_min_roi=param.get("competingMinRoi"),
                                              is_test_execute=param["isTestExecute"])()

        result_path, file_suffix = gjc_hyc_run(param, competing_path)
        return {
            'task_file_base64': Base64Util.file_to_base64(result_path, is_remove=False),
            'task_file_suffix': file_suffix
        }
    finally:
        if param["ScreenAction"]:
            # 如果开启录屏则停止录屏
            screen.abort_capture()
        ExcelUtil.xw_close_all_excel()


@backoff.on_exception(backoff.constant, Exception, max_tries=5,
                      interval=5, on_backoff=lambda details: log_.error(traceback.format_exc()),
                      giveup=lambda ex: isinstance(ex, LoginError))
@backoff.on_predicate(backoff.fibo, lambda e: isinstance(e, (LoginError,)), max_tries=1)
# 重试装饰器  重试3次 每次间隔5秒 遇到LoginError错误则不重试
def task_operaiton_gjc_run(snapshot, other):
    if snapshot.get("ScreenAction"):
        # 如果开启录屏，就录屏
        screen.start_capture()
    param = snapshot.get('param')
    log_.info(f"任务参数 : param {param}")
    for search_obj in param["searchObjList"]:
        try:
            log_.info(f"开始执行关键词 : {search_obj['searchContent']}")
            datalist = SearchRank(search_obj)()
            keywords = datalist["关键词"].tolist()
            keywords_obj = RelatedAnalysis(search_obj, keywords)()
            category = search_obj["searchContent"]
            requests_data("post", uri="public/operationAid/KeyWord/add", params={
                "categoryName": category,
                "dataList": keywords_obj
            }, req_title="运营助手-获取市场关键词", req_is_log=True, req_param_is_log=False)
        finally:
            if snapshot.get("ScreenAction"):
                # 如果开启录屏则停止录屏
                screen.abort_capture()
            # page.run_js('alert("已完成");')


def task_product_single_run(snapshot, other):
    """执行获取流量来源数据"""
    param = snapshot.get('param')
    log_.info(f"任务参数 : param {param}")
    log_.info("开始执行获取流量来源数据")
    product_single_task(param)


def task_store_info_run(snapshot, other):
    """执行获取淘宝店铺信息"""
    param = snapshot.get('param')
    log_.info(f"任务参数 : param {param}")
    log_.info("开始执行获取店铺信息")
    store_info_list = StoreInfo(param)()
    for store_info in store_info_list:
        time.sleep(1)
        # 这里写将store_info_json到java中台接口发送
        log_.info(f"{store_info}")
        requests_data("post", uri="public/store/tb/commit", params=store_info,
                      req_title="运营助手-获取店铺信息",
                      req_is_log=True, req_param_is_log=False)


def task_pdd_store_info_run(snapshot, other):
    """拼多多店铺信息"""
    from autoTask.operaitonAid.pinduoduo.goods_effect.get_goods_effect import Task as pdd_goods_effect
    param = snapshot.get('param')
    log_.info(f"任务参数 param {param} email: {other.get('adEmail')}")
    if param['defYesterday'] in [True, 'True', 'true']:
        param['queryTimeList'] = [DateUtil.get_yesterday()]
    PinDuoDuo_Login(param['account'], param['password'], email=other.get('adEmail')).action()
    pdd_goods_effect(param['queryTimeList']).run()


def find_market_rank_to_system(snapshot, other):
    """
    获取竞品(排行榜商品)载入系统中
    :param other:
    :param snapshot: 任务快照
    :return:
    """
    param: dict = snapshot.get('param')
    # 校验参数
    FindMarketRankToSystem.check_param(param)
    page, _ = Login(param.get("account"), param.get('password')).execute(
        url="https://sycm.taobao.com/portal/home.htm")
    tb_slider(page, timeout=10)
    FindMarketRankToSystem(page=page, category=param.get('category'), date_cycle=param.get('dateCycle'))()


def task_pdd_effect_detail(snapshot, other):
    """拼多多商品信息"""
    from autoTask.operaitonAid.pinduoduo.goods_effect.goods_effect_detail import Task as pdd_goods_effect_detail
    param = snapshot.get('param')
    log_.info(f"任务参数 : param {param} {other.get('adEmail')}")
    PinDuoDuo_Login(param['account'], param['password'], email=other.get('adEmail')).action()
    pdd_goods_effect_detail().run()


def tb_sku_monitor(snapshot, other):
    """
    淘宝 sku 监控
    :param other:
    :param snapshot:
    :return:
    """
    from autoTask.operaitonAid.taobao.product.sku_monitor import SkuMonitor
    p = web_page_util.create_page()
    SkuMonitor(p, other.get('adId'), snapshot.get('pushTaskId'),
               snapshot.get('param').get('productIds'))()


def sycm_market_rank_goods(snapshot, other):
    p = web_page_util.create_page()
    params = snapshot.get("param")
    Login(params.get('account'), params.get('password'), p).execute()
    from autoTask.taobao.sycm.market_rank.item import Main1
    from autoTask.taobao.enum import WebPlugin
    from autoTask.taobao.sycm.market_rank.item import FilterParam
    filter_param = params.get("filterParam")

    path = Main1(params.get('categoryList'), params.get('dateCycle'), p, WebPlugin.XSW
                 , FilterParam(filter_param.get('miniPayer'), filter_param.get('g1MiniAmount'),
                               filter_param.get("g1MiniUV")))()
    if params.get('handlerResultMode') == 0:
        return {
            'task_file_base64': Base64Util.file_to_base64(path),
            'task_file_suffix': "xlsx"
        }


# 任务映射 key: 数据库的任务id , value 本地 python 的 方法
task_mapping = {
    '3': test,
    '4': task_gjc_hyc_run,
    '5': competitor_good_key,
    '6': find_market_rank,
    '2': ztc_gjc_opti_bid,
    '7': task_operaiton_gjc_run,
    '8': task_product_single_run,
    '9': task_store_info_run,
    '10': task_pdd_store_info_run,
    '11': find_market_rank_to_system,
    '12': task_pdd_effect_detail,
    '101': tb_sku_monitor,
    '102': sycm_market_rank_goods,
}
